const MongoClient = require('mongodb').MongoClient;
const EventEmitter = require('events').EventEmitter

const conf = require('../conf')

let getClient = (url) => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, (err, client) => {
            if (err) {
                reject(err)
            } else {
                resolve(client)
            }
        })
    })
}

class MongoDb {
    constructor(conf) {
        this.conf = conf
        this.client = null
        this.emitter = new EventEmitter()

        getClient(conf.url)
            .then((client) => {
                this.client = client
                console.log('数据库连接成功')
                this.emitter.emit('connect')
            }, (err) => {
                throw err
            })
    }

    once(event, cb) {
        this.emitter.once(event, cb)
    }

    // 获取集合
    col(colName, dbName = this.conf.dbName) {
        return this.client.db(dbName).collection(colName)
    }
}

module.exports = new MongoDb(conf)
